//
//  GPSInfoBaseView.m
//  Yihubang
//
//  Created by xmy on 2016/12/8.
//  Copyright © 2016年 xmy. All rights reserved.
//

#import "GPSInfoBaseView.h"
#import "HelpContractCell.h"
#import "AVPlayerItem+MCCacheSupport.h"
@interface GPSInfoBaseView ()
@property (strong ,nonatomic) AVPlayer    * player;
@property (strong ,nonatomic) NSIndexPath * playingIndex;
@property (strong ,nonatomic) RACCommand  * preparePlayCommend;
@end
@implementation GPSInfoBaseView

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/
-(void)awakeFromNib{
    [super awakeFromNib];
    self.info_tableView.estimatedRowHeight = 55.f ;
    [self.info_tableView registerNib:[UINib nibWithNibName:@"HelpContractCell" bundle:nil] forCellReuseIdentifier:@"HelpContractCell"];
    @weakify(self);
    self.contractCommend = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
        @strongify(self);
        [self.contractCommend execute:input];
        return [RACSignal empty];
    }];
    self.preparePlayCommend = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(NSArray * dataSource) {
        @strongify(self);
        if(dataSource[0][@"listened"]){
            [self.exChangeCommend execute:dataSource[1]];
        }
        [self prepareToPlay:dataSource];
        return [RACSignal empty];
    }];
}
-(void) prepareToPlay:(NSArray *) dataSource{
    if(self.playingIndex !=nil ){
        [self clearPlayerAndAnimation];
        if([dataSource[1] integerValue] == self.playingIndex.row){
            return;
        }
    }
    if([dataSource[0][@"wav_url"] length] >11){
        [self playWithurl:dataSource[0][@"wav_url"] And:dataSource[1]];
    }else{
        @weakify(self);
        [self.superViewController showHUDWithString:@""];
        [[[HttpManagerCenter sharedHttpManager] getVoiceUrl:dataSource[0] resultClass:nil] subscribeNext:^(BaseModel *model){
            @strongify(self)
            if(model.code==200){
                [self.superViewController hiddenHUD];
                 [self.exChangeCommend execute:@[dataSource[1],model.data[@"wav_url"]]];
                [self playWithurl:model.data[@"wav_url"] And:dataSource[1]];
                
            }
        }];
    }
}
-(void)playWithurl:(NSString *)url And:(id)index{
    NSError *playerError;
    AVPlayerItem *item = [AVPlayerItem mc_playerItemWithRemoteURL:[NSURL URLWithString:[url masterFullImageUrl]] error:&playerError];
    self.player = [[AVPlayer alloc] initWithPlayerItem:item];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playbackFinished:) name:AVPlayerItemDidPlayToEndTimeNotification object:self.player.currentItem];
    if(playerError){
        NSLog(@"ERror creating player: %@", [playerError description]);
        return;
    }
    [self.player play];
    NSIndexPath * indexPath = [NSIndexPath indexPathForRow:[index integerValue] inSection:0];
    HelpContractCell * cell = [self.info_tableView cellForRowAtIndexPath:indexPath];
    self.playingIndex=indexPath;
    [cell.hearRecorder startAnimating];
}
-(void)playbackFinished:(NSNotification *)notification{
    [self clearPlayerAndAnimation];
}
-(void)clearPlayerAndAnimation{
    [self.player pause];
    self.player=nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    HelpContractCell * cell = [self.info_tableView cellForRowAtIndexPath:self.playingIndex];
    [cell.hearRecorder stopAnimating];
    cell=nil;
}


-(NSMutableArray *)dataSource{
    if(!_dataSource){
        _dataSource = [NSMutableArray new];
    }
    return _dataSource;
}

-(void)viewResetWithType:(GPSInfoBaseViewReckIndex)index DataSource:(id)dataSource{
    switch (index) {
        case 0:
            self.titleView_label.text = @"对方录制的语音列表";
            self.layoutConstraint_top.constant = 89.f;
            self.layoutConstraint_buttonLeft.constant = 12.f;
            break;
            
        case 1:
            self.titleView_label.text = @"对方录制的语音列表";
             self.layoutConstraint_top.constant = ScreenWidth /375 * 142 + 65;
            self.layoutConstraint_buttonLeft.constant =ScreenWidth - 62.f;
            break;
        case 2:
            self.titleView_label.text = @"对方其余紧急联系人";
            self.layoutConstraint_top.constant = 209.f;
            self.layoutConstraint_buttonLeft.constant = 12.f;
            break;
        case 3:
            self.titleView_label.text = @"对方其余紧急联系人";
            self.layoutConstraint_top.constant = ScreenWidth /375 * 142 + 130;
            self.layoutConstraint_buttonLeft.constant = 12.f;
            break;
    }
    self.index = index;
    self.dataSource = [NSMutableArray arrayWithArray:dataSource];
    [self.info_tableView reloadData];
}
- (IBAction)removeSelfVew:(id)sender {
    [UIView animateWithDuration:0.6 animations:^(void){
        self.alpha =0.0f;
    } completion:^(BOOL finish){
        [self removeFromSuperview];
        if(self.player){
            [self clearPlayerAndAnimation];
        }
    }];
}

#pragma UITableView DateSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.dataSource count];
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HelpContractCell *cell = (HelpContractCell *)[tableView  dequeueReusableCellWithIdentifier:@"HelpContractCell"];
    if (self. index >1){
        [cell showSbContract:self.dataSource[indexPath.row]];
        cell.contractCommend =self.contractCommend;
    }else{
        [cell showRecoder:self.dataSource[indexPath.row] AndIndex:indexPath.row];
        cell.preparePlayCommend = self.preparePlayCommend;
    }
    return cell;
}
@end
